// app/vendor/responses/page.tsx
import * as React from "react";
import Link from "next/link";
import { Metadata } from "next";
import { getServerSession } from "next-auth/next";
import { authOptions } from "@/app/api/auth/[...nextauth]/route";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { LogIn, FileX, Clock, CheckCircle, AlertTriangle } from "lucide-react";
import { DataTableSkeleton } from "@/components/data-table/data-table-skeleton";
import { Shell } from "@/components/shell";
import { getValidFilters } from "@/lib/data-table";
import { type SearchParams } from "@/types/table";
import { searchParamsVendorResponseCache } from "@/lib/b-rfq/validations";
import { getVendorResponseProgress, getVendorResponseStatusCounts, getVendorRfqResponses } from "@/lib/b-rfq/service";
import { VendorResponsesTable } from "@/lib/b-rfq/vendor-response/vendor-responses-table";
import { InformationButton } from "@/components/information/information-button"
export const metadata: Metadata = {
  title: "응답 관리",
  description: "RFQ 첨부파일 응답 현황을 관리합니다",
};

interface IndexPageProps {
  searchParams: Promise<SearchParams>
}

export default async function IndexPage(props: IndexPageProps) {
  const searchParams = await props.searchParams
  const search = searchParamsVendorResponseCache.parse(searchParams)
  const validFilters = getValidFilters(search.filters)
  
  // 인증 확인
  const session = await getServerSession(authOptions);
  
  // 로그인 확인
  if (!session || !session.user) {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <div className="flex items-center gap-2">
              <h2 className="text-2xl font-bold tracking-tight">
                응답 관리
              </h2>
              <InformationButton pagePath="partners/rfq-answer" />
            </div>
            {/* <p className="text-muted-foreground">
              RFQ 첨부파일 응답 현황을 확인하고 관리합니다.
            </p> */}
          </div>
        </div>

        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">로그인이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              응답 현황을 확인하려면 먼저 로그인하세요.
            </p>
            <Button size="lg" asChild>
              <Link href="/partners?callbackUrl=/vendor/responses">
                <LogIn className="mr-2 h-4 w-4" />
                로그인하기
              </Link>
            </Button>
          </div>
        </div>
      </Shell>
    );
  }
  
  // 벤더 ID 확인
  const vendorId = session.user.companyId ? String(session.user.companyId) : "0";
  
  // 벤더 권한 확인
  if (session.user.domain !== "partners") {
    return (
      <Shell className="gap-6">
        <div className="flex items-center justify-between">
          <div>
            <h2 className="text-2xl font-bold tracking-tight">
              접근 권한 없음
            </h2>
          </div>
        </div>
        <div className="flex flex-col items-center justify-center py-12 text-center">
          <div className="rounded-lg border border-dashed p-10 shadow-sm">
            <h3 className="mb-2 text-xl font-semibold">벤더 계정이 필요합니다</h3>
            <p className="mb-6 text-muted-foreground">
              벤더 계정으로 로그인해주세요.
            </p>
          </div>
        </div>
      </Shell>
    );
  }
  
  // 데이터 가져오기
  const responsesPromise = getVendorRfqResponses({
    ...search,
    filters: validFilters
  }, vendorId);
  
  // 상태별 개수 및 진행률 가져오기
  const [statusCounts, progress] = await Promise.all([
    getVendorResponseStatusCounts(vendorId),
    getVendorResponseProgress(vendorId)
  ]);
  
  // 프로미스 배열
  const promises = Promise.all([responsesPromise]);
  
  return (
    <Shell className="gap-6">
      <div className="flex justify-between items-center">
        <div>
          <h2 className="text-2xl font-bold tracking-tight">RFQ 응답 관리</h2>
          <p className="text-muted-foreground">
            RFQ 첨부파일 응답 현황을 확인하고 관리합니다.
          </p>
        </div>
      </div>
      
      {/* 상태별 통계 카드 */}
      <div className="grid gap-4 md:grid-cols-2 lg:grid-cols-5">
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">전체 요청</CardTitle>
            <FileX className="h-4 w-4 text-muted-foreground" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold">{progress.totalRequests}건</div>
            <p className="text-xs text-muted-foreground">
              총 응답 요청 수
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">미응답</CardTitle>
            <Clock className="h-4 w-4 text-orange-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-orange-600">
              {statusCounts.NOT_RESPONDED || 0}건
            </div>
            <p className="text-xs text-muted-foreground">
              응답 대기 중
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">응답완료</CardTitle>
            <CheckCircle className="h-4 w-4 text-green-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-green-600">
              {statusCounts.RESPONDED || 0}건
            </div>
            <p className="text-xs text-muted-foreground">
              응답률: {progress.responseRate}%
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">수정요청</CardTitle>
            <AlertTriangle className="h-4 w-4 text-yellow-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-yellow-600">
              {statusCounts.REVISION_REQUESTED || 0}건
            </div>
            <p className="text-xs text-muted-foreground">
              재검토 필요
            </p>
          </CardContent>
        </Card>
        
        <Card>
          <CardHeader className="flex flex-row items-center justify-between space-y-0 pb-2">
            <CardTitle className="text-sm font-medium">포기</CardTitle>
            <FileX className="h-4 w-4 text-gray-600" />
          </CardHeader>
          <CardContent>
            <div className="text-2xl font-bold text-gray-600">
              {statusCounts.WAIVED || 0}건
            </div>
            <p className="text-xs text-muted-foreground">
              완료율: {progress.completionRate}%
            </p>
          </CardContent>
        </Card>
      </div>
      
      <React.Suspense
        fallback={
          <DataTableSkeleton
            columnCount={8}
            searchableColumnCount={2}
            filterableColumnCount={3}
            cellWidths={["10rem", "12rem", "8rem", "10rem", "10rem", "8rem", "10rem", "8rem"]}
          />
        }
      >
        <VendorResponsesTable promises={promises} />
      </React.Suspense>
    </Shell>
  );
}